<template>
	<div class="board-container">
		<div class="filter-container mb-[10px] flex items-center gap-4 flex-wrap">
            城市：
			<el-select
				v-model="cityId"
				placeholder="全部"
				style="max-width: 120px; min-width: 100px"
			>
				<el-option label="全部" value=""></el-option>
				<template v-for="item in cityList" :key="item.value">
					<el-option :label="item.label" :value="item.value" />
				</template>
			</el-select>
            门店：
			<el-select
				v-model="shopId"
				placeholder="全部"
				style="max-width: 120px; min-width: 100px"
			>
				<el-option label="全部" value=""></el-option>
				<template v-for="item in shopList" :key="item.value">
					<el-option :label="item.label" :value="item.value" />
				</template>
			</el-select>
            商品：
			<el-select
				v-model="goodsMoney"
				placeholder="全部"
				style="max-width: 120px; min-width: 100px"
			>
				<el-option label="全部" value=""></el-option>
				<template v-for="item in goodsList" :key="item.value">
					<el-option :label="item.label" :value="item.value" />
				</template>
			</el-select>
		</div>
		<div class="table-wrapper">
			<el-table 
				:data="tableData" 
				border 
				:span-method="objectSpanMethod"
				style="width: 100%"
				row-key="rowKey"
			>
				<el-table-column 
					label="城市" 
					prop="cityName"
					min-width="120"
				>
				</el-table-column>
				<el-table-column 
					label="门店" 
					prop="shopName"
					min-width="120"
				>
				</el-table-column>
				<el-table-column 
					label="订单数" 
					prop="orderCount"
					min-width="80"
					align="center"
				>
				</el-table-column>
				<el-table-column 
					label="金额" 
					prop="amount"
					min-width="100"
					align="center"
				>
				</el-table-column>
			</el-table>
		</div>
	</div>
</template>

<script lang="ts" setup>
defineOptions({
	name: 'appointment-board'
});

import { useCool } from '/@/cool';
import { onMounted, ref, watch, computed } from 'vue';
import dayjs from 'dayjs';

const { service } = useCool();

// 定义数据类型接口
export interface ShopData {
	cityName: string;
	shopName: string;
	orderCount: number;
	amount: number;
	isTotal?: boolean;
	isCityTotal?: boolean;
	goodsMoney?: string;
	rowKey?: string; // 添加行键用于表格
}

const tableData = ref<ShopData[]>([]);
const cityId = ref('');
const shopId = ref('');
const goodsMoney = ref('');
const appointmentTime = ref([
	dayjs().subtract(7, 'day').format('YYYY-MM-DD'),
	dayjs().format('YYYY-MM-DD')
]);



// 监听城市变化
watch(cityId, () => {
	getData();
});

// 监听门店变化
watch(shopId, () => {
	getData();
});

// 监听商品变化
watch(goodsMoney, () => {
	getData();
});


onMounted(async () => {
    getSelection();
	getData();
});

const cityList = ref([]);
const shopList = ref([]);
const goodsList = ref([]);

async function getSelection() {
    const res = await service.order.city.getCityList({});
    if (res) {
        cityList.value = Object.values(res);
    }
    const res2 = await service.order.shop.getSelectList({});
    if (res2) {
        shopList.value = Object.values(res2);
    }
    // const res3 = await service.order.goods.getSelectList({});
    goodsList.value = [
        {
            label: '医疗版',
            value: '3980'
        },
        {
            label: '标准版',
            value: '2680'
        }
    ];
}

// 获取数据
async function getData() {
	const params = {
        cityId: cityId.value,
        shopId: shopId.value,
        goodsMoney: goodsMoney.value
	};

	const res: Record<string, any> = await service.order.city.tongkangShopBoard(params)
    const processedData: ShopData[] = [];
    const cityMap = new Map<string, number>();
    let rowIndex = 0;
    
    // 遍历所有城市数据
    if (res) {
        Object.values(res).forEach((cityData: any) => {
            // 遍历每个城市的门店数组
            if (cityData.shopArr && Array.isArray(cityData.shopArr)) {
                const cityName = cityData.shopArr[0]?.cityName || '';
                let cityTotalOrderCount = 0;
                let cityTotalAmount = 0;
                const shopCount = cityData.shopArr.length || 0;
                
                // 存储每个城市的门店数据
                const shopData: ShopData[] = [];
                
                cityData.shopArr.forEach((shop: any) => {
                    shopData.push({
                        cityName: shop.cityName,
                        shopName: shop.shopName,
                        orderCount: shop.orderCount,
                        amount: shop.amount,
                        isTotal: false,
                        rowKey: `shop_${rowIndex++}`
                    });
                    
                    // 计算城市合计
                    cityTotalOrderCount += shop.orderCount || 0;
                    cityTotalAmount += shop.amount || 0;
                });
                
                // 添加门店数据到处理后的数据中
                processedData.push(...shopData);
                
                // 添加城市合计行
                processedData.push({
                    cityName: '合计',
                    shopName: shopCount,
                    orderCount: cityTotalOrderCount,
                    amount: cityTotalAmount,
                    isTotal: true,
                    isCityTotal: true,
                    rowKey: `total_${rowIndex++}`
                });
                
                // 记录城市对应的行数（门店数+1行合计）
                cityMap.set(cityName, shopData.length);
            }
        });
    }
    
    tableData.value = processedData;
    // 保存城市映射供合并单元格使用
    cityRowMap.value = cityMap;
}

// 存储城市对应的行数
const cityRowMap = ref(new Map<string, number>());

// 合并单元格方法
function objectSpanMethod({ row, column, rowIndex, columnIndex }) {
    // 处理城市列的合并
    if (columnIndex === 0) {
        // 如果是合计行，不合并
        if (row.isTotal) {
            return { rowspan: 1, colspan: 1 };
        }
        
        const cityName = row.cityName;
        
        // 检查当前行是否是城市的第一行
        let isFirstRow = true;
        for (let i = rowIndex - 1; i >= 0; i--) {
            if (tableData.value[i] && tableData.value[i].cityName === cityName && !tableData.value[i].isTotal) {
                isFirstRow = false;
                break;
            }
        }
        
        if (isFirstRow) {
            // 计算当前城市需要合并的行数
            let rowspan = 0;
            for (let i = rowIndex; i < tableData.value.length; i++) {
                if (tableData.value[i] && tableData.value[i].cityName === cityName && !tableData.value[i].isTotal) {
                    rowspan++;
                } else {
                    break;
                }
            }
            return { rowspan, colspan: 1 };
        } else {
            // 非第一行的城市单元格不显示
            return { rowspan: 0, colspan: 0 };
        }
    }
    
    // 处理其他列
    return { rowspan: 1, colspan: 1 };
}
</script>

<style scoped>
.board-container {
  padding: 20px;
  box-sizing: border-box;
}

.filter-container {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.table-wrapper {
  max-height: calc(100vh - 200px); /* 确保表格不会超出页面高度 */
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 8px;
}

/* 表格滚动条样式 */
.table-wrapper::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.table-wrapper::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.table-wrapper::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 4px;
}

.table-wrapper::-webkit-scrollbar-thumb:hover {
  background: #909399;
}

/* 确保表格可以水平滚动 */
:deep(.el-table) {
  min-width: 100%;
  width: auto;
}

/* 合计行样式 */
:deep(.el-table__row.is-total-row) {
  background-color: #fafafa !important;
  font-weight: bold;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .board-container {
    padding: 10px;
  }
  
  .filter-container {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-container .el-select {
    width: 100%;
    max-width: none;
    margin-bottom: 10px;
  }
}
</style>
